package cn.edu.zime.tjh47;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class Class12_2 extends AppCompatActivity {
    private TextView textView;
    private EditText editText;

    // 创建一个 Handler
    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            String res;
            switch (msg.what) {
                case 0:
                    res = (String) msg.obj;
                    if (res == null || res.equals("")) {
                        textView.setText("服务返回空值");
                    } else {
                        textView.setText(res);
                    }
                    break;
                case 1:
                    res = (String) msg.obj;
                    textView.setText("网络服务错误" + res);
                    break;
            }
            return true;
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.class12_2);
        textView = findViewById(R.id.tv_webview);
        editText = findViewById(R.id.et_url);
    }

    public void go(View view) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String result = getNetData();

                    // 使用 Handler 将结果传递到主线程
                    Message message = new Message();
                    message.obj = result;
                    message.what = 0;
                    handler.sendMessage(message);
                } catch (IOException e) {
                    e.printStackTrace();

                    // 发送错误消息
                    Message message = new Message();
                    message.obj = e.getMessage();
                    message.what = 1;
                    handler.sendMessage(message);
                }
            }
        }).start();
    }

    private String getNetData() throws IOException {
        URL url = new URL(editText.getText().toString());
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.connect();

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder result = new StringBuilder();
        String line;

        while ((line = bufferedReader.readLine()) != null) {
            result.append(line);
        }

        return result.toString();
    }

    public void back(View view) {
        finish();
    }
}
